package cn.tedu.straw.api.service.impl;


import cn.tedu.straw.api.dto.PostCommentDTO;
import cn.tedu.straw.api.ex.AccessDeniedException;
import cn.tedu.straw.api.ex.CommentNotFoundException;
import cn.tedu.straw.api.ex.DeleteException;
import cn.tedu.straw.api.ex.InsertException;
import cn.tedu.straw.api.mapper.CommentMapper;
import cn.tedu.straw.api.service.ICommentService;
import cn.tedu.straw.commons.model.Comment;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2020-08-11
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Override
    public Comment post(PostCommentDTO postCommentDTO, Integer userid, String userNickNmae) {
        Comment comment = new Comment();
        comment.setAnswerId(postCommentDTO.getAnswerId())
                .setContent(postCommentDTO.getContent())
                .setUserId(userid)
                .setUserNickName(userNickNmae)
                .setCreatedTime(LocalDateTime.now());
        int rows = commentMapper.insert(comment);
        if (rows != 1) {
            throw new InsertException("服务器繁忙！请稍后再次尝试！");
        }
        return comment;
    }

    @Override
    public Comment delete(Integer commentId, Integer userId) {
        // 获取评论数据
        Comment result = commentMapper.selectById(commentId);
        // 判断数据是否存在
        if (result == null) {
            throw new CommentNotFoundException("删除评论失败！尝试访问的数据不存在！");
        }
        // 判断是否具有权限操作数据
        if (!result.getUserId().equals(userId)) {
            throw new AccessDeniedException("删除评论失败！权限不足，不能删除！");
        }
        // 删除评论
        int rows = commentMapper.deleteById(commentId);
        if (rows!=1){
            throw new DeleteException("删除失败！服务器忙，请稍后再次尝试！");
        }
        // 返回结果
        return result;
    }
}
